import { createAlova } from 'alova'
import { notification } from 'antd'
import ReactHook from 'alova/react'
import GlobalFetch from 'alova/GlobalFetch'

import { API_LIST } from './API'
import { GetIndexedDB } from '../Utils/IndexedDB'

const codeMessage = {
  200: '服务器成功返回请求的数据。',
  201: '新建或修改数据成功。',
  202: '一个请求已经进入后台排队（异步任务）。',
  204: '删除数据成功。',
  400: '发出的请求有错误。',
  401: '用户没有权限（令牌、用户名、密码错误）。',
  403: '用户得到授权，但是访问是被禁止的。',
  404: '发出的请求针对的是不存在的记录。',
  406: '请求的格式不可得。',
  410: '请求的资源被永久删除，且不会再得到的。',
  422: '当创建一个对象时，发生一个验证错误。',
  500: '服务器发生错误，请检查服务器。',
  502: '网关错误。',
  503: '服务不可用，服务器暂时过载或维护。',
  504: '网关超时。',
  521: '接口又爱了'
}

const alovaInstance = createAlova({
  localCache: null,
  timeout: 30000,
  statesHook: ReactHook,
  requestAdapter: GlobalFetch(),
  async beforeRequest(method) {
    const { url } = method
    const TypeXFrom = [
      API_LIST()['posToken'],
      API_LIST()['posEzvizStart'],
      API_LIST()['posEzvizStop'],
      API_LIST()['posEzvizStop']
    ]
    const urlsToMatch = [
      API_LIST()['getProjectConfigInfo'],
      API_LIST()['getTokenByQRUuid'],
      API_LIST()['getToKenByProjectUuid'],
      API_LIST()['getWeatherNow'],
      API_LIST()['getGetOneBeamProduce'],
      API_LIST()['posAIInteraction'],
      API_LIST()['getCameras'],
      'http://123.57.220.90:8909/project',
    ]

    if (TypeXFrom.includes(url)) {
      method.config.headers['content-type'] = 'application/x-www-form-urlencoded'
    } else if (urlsToMatch.includes(url)) {
      method.config.headers['content-type'] = 'application/json; charset=utf-8'
    } else {
      const token = await GetIndexedDB('token')
      if (token) {
        method.config.headers['content-type'] = 'application/json; charset=utf-8'
        method.config.headers.Authorization = token
      } else { throw new Error('请求头失效') }
    }
  },
  responded: {
    onSuccess: async (response) => {
      try {
        const json = await response.json()
        if (response.status >= 400) {
          ErrorModal(response.status, json)
          throw new Error(json)
        }
        return json
      }
      catch (err) {
        throw new Error(err)
      }
    },
    onError: (error) => console.log('error', error)
  }
})

export const Http = ({ url, params, path, headers }) => {
  switch (url.substring(0, 3)) {
    case 'get':
      return alovaInstance.Get(API_LIST(path)[url], { params, headers })
    case 'pos':
      return alovaInstance.Post(API_LIST(path)[url], params)
    case 'put':
      return alovaInstance.Put(API_LIST(path)[url], params)
    case 'del':
      return alovaInstance.Delete(API_LIST(path)[url], params)
    case 'pat':
      return alovaInstance.Patch(API_LIST(path)[url], params)
    default: return false
  }
}

const ErrorModal = (status, data) => {
  const { error, msg, detail } = data

  const errMapping = { 'invalid_grant': '用户名密码错误' }

  notification.error({
    message: codeMessage[status],
    description: errMapping[error] || msg || detail || JSON.stringify(data) || '未知报错信息'
  })
}